//
//  JFTRequest.m
//  JftMergeSDK
//
//  Created by zhl on 2017/2/10.
//  Copyright © 2017年 HLZ. All rights reserved.
//

#import "JFTRequest.h"
#import <SystemConfiguration/SCNetworkReachability.h>
#import <UIKit/UIKit.h>
#import "JFTDES.h"
#import "JFTConfigureHeader.h"
#import <netinet/in.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>
#import <CoreTelephony/CTCarrier.h>
#import "NSData+AES.h"
@interface JFTRequest()
@property (nonatomic,strong)NSURLSession*session;
@end
@implementation JFTRequest
+(instancetype)requestManager{
    static JFTRequest *shareRequest =nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        shareRequest =[self new];
    });
    return shareRequest;
    
}
-(NSURLSession *)session{
    if (!_session) {
        _session =[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    }
    return _session;
    
}
-(BOOL)ConnectedToNetwork
{
    // Create zero addy
    struct sockaddr_in zeroAddress;
    bzero(&zeroAddress, sizeof(zeroAddress));
    zeroAddress.sin_len = sizeof(zeroAddress);
    zeroAddress.sin_family = AF_INET;
    // Recover reachability flags
    SCNetworkReachabilityRef defaultRouteReachability = SCNetworkReachabilityCreateWithAddress(NULL, (struct sockaddr *)&zeroAddress);
    SCNetworkReachabilityFlags flags;
    
    BOOL didRetrieveFlags = SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags);
    CFRelease(defaultRouteReachability);
    
    if (!didRetrieveFlags)
    {
        printf("Error. Could not recover network reachability flags\n");
        return NO;
    }
    BOOL isReachable = ((flags & kSCNetworkFlagsReachable) != 0);
    BOOL needsConnection = ((flags & kSCNetworkFlagsConnectionRequired) != 0);
    return (isReachable && !needsConnection) ? YES : NO;
}


- (void)getDataWithUrl:(NSURL *)url WithParameters:(NSDictionary *)parDictionary Sucessfil:(void (^)(id))Sucessful failure:(void (^)(id failerObjc))failure error:(void (^)(NSError * err))errorBlock{
    if (![self ConnectedToNetwork]) {
        failure (@"没有网络连接");
        return;
    }    
    NSMutableURLRequest *mutableUrlRequest =[NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20];
//    NSURLSession *session1 =[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDataTask *task =[self.session dataTaskWithRequest:mutableUrlRequest completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            errorBlock(error);
            return ;
        }
         NSHTTPURLResponse *ponse =(NSHTTPURLResponse*)response;

        if (ponse.statusCode!=200) {
        failure([NSString stringWithFormat:@"%ld",(long)ponse.statusCode]);
            return;
        }
        NSError*jsonError=nil;
        id returnData =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
        if (jsonError) {
            errorBlock(jsonError);
            return;
        }
        if (returnData) {
            Sucessful (returnData);
        }
    }];
    [task resume];
}

- (void)postDataWithUrl:(NSURL *)url WithParameters:(NSDictionary*)parDictionary Sucessfil:(void (^)(id returnData))Sucessful failure:(void (^)(id failerObjc))failure error:(void (^)(NSError * err))errorBlock{
    if (![self ConnectedToNetwork]) {
        failure (@"没有网络连接");
        return;
    }
    NSMutableArray *mutableArray =[NSMutableArray new];
    NSArray *keyArray =[parDictionary allKeys];
    NSArray *valueArray =[parDictionary allValues];
    for (int i=0; i<keyArray.count; i++) {
        [mutableArray addObject:[NSString stringWithFormat:@"%@=%@",keyArray[i],valueArray[i]]];
    }
    NSLog(@"%@",[mutableArray componentsJoinedByString:@"&"]);
    NSString*compoentString =[mutableArray componentsJoinedByString:@"&"];
    NSMutableURLRequest *mutableUrlRequest =[NSMutableURLRequest requestWithURL:url cachePolicy:1 timeoutInterval:25];
    mutableUrlRequest.HTTPMethod =@"POST";
    mutableUrlRequest.HTTPBody=[compoentString dataUsingEncoding:NSUTF8StringEncoding];
//     [mutableUrlRequest addValue: @"text/html; charset=utf-8" forHTTPHeaderField:@"Content-Type"];
//    NSURLSession *session =[NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:[NSOperationQueue mainQueue]];
    NSURLSessionDataTask *task =[self.session dataTaskWithRequest:mutableUrlRequest  completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        if (error) {
            errorBlock(error);
            return ;
        }
        NSHTTPURLResponse *ponse =(NSHTTPURLResponse*)response;
        if (ponse.statusCode!=200) {
            failure([NSString stringWithFormat:@"%ld",(long)ponse.statusCode]);
            return;
        }
        NSError*jsonError;
        id returnData =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&jsonError];
        Sucessful (returnData);
        
    }];
    [task resume];
}
- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * __nullable credential))completionHandler{
    completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
}
//- (void)submitInfo:(JFTExceptionModel*)model andUrl:(NSString *)postUrl{
//    if (model) {
//        [JFTFileManager addaModel:model];
//            }
//    NSMutableDictionary *endic =[JFTFileManager readAllData];
//    if (!endic) {
//        return;
//    }
//    NSLog(@"%@",endic);
//    NSData *mmdata =[NSJSONSerialization dataWithJSONObject:endic options:NSJSONWritingPrettyPrinted error:nil];
//    NSString *enStr=[[NSString alloc]initWithData:mmdata encoding:NSUTF8StringEncoding];
//    NSString*miwen =   [JFTDES encryptWithContent:enStr type:0 key:[[JFTDES md532BitUpper:[JFTDESKEY stringByAppendingString:@"abcdefg"]] substringToIndex:8]];
//    NSString *specalStr =[JFTDES replacenormalcharacter:miwen];
//    NSString *encodeURL =[JFTDES encodeToPercentEscapeString:specalStr];
//    NSString *myUrlString =[NSString stringWithFormat:@"%@/sdk/UploadTheLog",postUrl];
//    NSURL *url=[NSURL URLWithString:myUrlString];
////    NSLog(@"%@",encodeURL);
//    [self postDataWithUrl:url WithParameters:[NSString stringWithFormat:@"nonce=abcdefg&info=%@",encodeURL] Sucessfil:^(id returnData) {
////        NSLog(@"%@",returnData);
//        if ([returnData isKindOfClass:[NSDictionary class]]) {
//            NSDictionary *returnDic =returnData;
//            if ([returnDic[@"flag"] boolValue]) {
//                NSString *ddstr=[NSString stringWithFormat:@"%@",[JFTDES replacespecialcharacter:returnDic[@"msg"]]];
//                NSString *keyyStr=[[JFTDES md532BitUpper:[JFTDESKEY stringByAppendingString:[returnDic objectForKey:@"nonce"]]] substringToIndex:8];
//                [JFTDES encryptWithContent:ddstr type:1 key:keyyStr];
//                NSString *jsonStr =[JFTDES encryptWithContent:ddstr type:1 key:keyyStr];
//                if ([[NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil] isKindOfClass:[NSDictionary class]]) {
//                    NSDictionary *jsonDic =[NSJSONSerialization JSONObjectWithData:[jsonStr dataUsingEncoding:NSUTF8StringEncoding] options:NSJSONReadingMutableLeaves error:nil];
////                    NSLog(@"%@",jsonDic);
//                    if ([jsonDic[@"uploadfew"] boolValue]) {
//                        
//                            [JFTFileManager deleteAll];
////                        NSLog(@"上传成功");
//                    }
//                }
//            
//                
//            }
//        }
//    } failure:^(id failerObjc) {
//        
//    } error:^(NSError *err) {
////        NSLog(@"%@",err);
//    }];
//
//}
@end
